// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// H [author] rhyme_lph
// t [email]  rhymelph@gmail.com
// W [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/a.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/fixed_asset_entity.dart';
import 'package:finance_app/src/entities/ocr_attachment_entity.dart';
import 'package:finance_app/src/utils/cash_utils.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/input_formatter_tools.dart';
import 'package:finance_app/src/widgets/button/normal_popup_button.dart';
import 'package:finance_app/src/widgets/button/normal_text_button.dart';
import 'package:finance_app/src/widgets/common/tag_widget.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/form/attach_file_form.dart';
import 'package:finance_app/src/widgets/form/form_edit_status_inherited_widget.dart';
import 'package:finance_app/src/widgets/form/value_select_form.dart';
import 'package:finance_app/src/widgets/input/form_input_field.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/all_reports/fixed_asset/new_fixed_asset_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:flutter_svg/svg.dart';
import 'package:tuple/tuple.dart';

@RouterMeta(paramName: "newFixedAssetPage")
class NewFixedAssetPage extends StatefulWidget {
  final int id;
  final FixedAssetEntity fixedAsset;

  const NewFixedAssetPage({Key key, this.id, this.fixedAsset})
      : super(key: key);

  @override
  _NewFixedAssetPageState createState() => _NewFixedAssetPageState();
}

class _NewFixedAssetPageState extends State<NewFixedAssetPage>
    with
        PagePresenter<NewFixedAssetPage, NewFixedAssetProvider>,
        WidgetsBindingObserver {
  String get title =>
      '${provider.id == null ? S.current.new_fixed_asset : provider.isEdit == true ? S.current.edit_fixed_asset : S.current.fixed_asset}';

  Widget get rightButton => listBuilder<bool>(
        selector: (_, __) => __.isEdit == false && provider.id != null,
        builder: (BuildContext context, bool value, Widget child) =>
            value == true ? _buildPopButton() : _buildSaveBtn(),
      );

  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
          titleWidget: listBuilder<Tuple2<bool, FixedAssetEntity>>(
            selector: (_, __) => Tuple2(__.isEdit, __.data),
            builder: (BuildContext context,
                    Tuple2<bool, FixedAssetEntity> value, Widget child) =>
                Text(title),
          ),
          actions: [
            rightButton,
          ]);

  Widget _buildPopButton() => listBuilder<List<String>>(
        selector: (_, __) => List.from(__.menuList),
        builder: (BuildContext context, List<String> value, Widget child) =>
            value.length == 0
                ? Container()
                : NormalMorePopupButton(
                    onSelect: provider.onSelectMenu,
                    menuList: provider.menuList,
                  ),
      );

  Widget _buildSaveBtn() {
    return listBuilder<bool>(
      selector: (_, __) => pageStatus != PageStatus.loading,
      builder: (BuildContext context, bool value, Widget child) => value == true
          ? NormalSaveTextButton(
              onTap: provider.onSave,
            )
          : Container(),
    );
  }

  @override
  Widget wrapperBody(Widget child) {
    return listBuilder<bool>(
        selector: (_, __) => __.isEdit == true || provider.id == null,
        builder: (BuildContext context, bool value, Widget child) =>
            FormEditStatusInheritedWidget(
              isEdit: value,
              child: child,
            ),
        child: child);
  }

  @override
  void initState() {
    provider.currency = Config.defaultCurrency;
    provider.depreciationMethod = Config.settingData.depreciationType.first;
    provider.init(widget.id);

    provider.initExpenseMode(widget.fixedAsset);
    WidgetsBinding.instance.addObserver(this);
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: ListView(
          children: [
            Stack(
              children: [
                FromInputField(
                  tip: S.current.asset_name,
                  controller: provider.assetNameController,
                  focusNode: provider.assetNameFocusNode,
                ),
                Align(
                  alignment: Alignment.centerRight,
                  child: listBuilder<bool>(
                    selector: (_, __) => __.isDisposed,
                    builder: (BuildContext context, bool value, Widget child) =>
                        value == true
                            ? Container(
                                margin: EdgeInsets.only(
                                    right: getDp(35), top: getDp(20)),
                                child: RedTagWidget(
                                  content: S.current.disposed,
                                ),
                              )
                            : Container(),
                  ),
                ),
                Align(
                  alignment: Alignment.centerRight,
                  child: listBuilder<bool>(
                    selector: (_, __) => __.isSold,
                    builder: (BuildContext context, bool value, Widget child) =>
                        value == true
                            ? Container(
                                margin: EdgeInsets.only(
                                    right: getDp(35), top: getDp(20)),
                                child: RedTagWidget(
                                  content: S.current.sold,
                                ),
                              )
                            : Container(),
                  ),
                ),
                Align(
                  alignment: Alignment.centerRight,
                  child: listBuilder<bool>(
                    selector: (_, __) => __.isDeleted,
                    builder: (BuildContext context, bool value, Widget child) =>
                        value == true
                            ? Container(
                                margin: EdgeInsets.only(
                                    right: getDp(35), top: getDp(20)),
                                child: RedTagWidget(
                                  content: 'Deleted',
                                ),
                              )
                            : Container(),
                  ),
                ),
              ],
            ),
            listBuilder<String>(
              selector: (_, __) =>
                  __.category?.name ?? widget.fixedAsset?.category,
              builder: (BuildContext context, String value, Widget child) =>
                  ValueSelectForm(
                title: S.current.category,
                value: value,
                onTap: provider.expenseMode ? null : provider.onChangeCategory,
              ),
            ),
            listBuilder<String>(
              selector: (_, __) => DateTimeUtils.formatGlobalDateTime(__.date),
              builder: (BuildContext context, String value, Widget child) =>
                  ValueSelectForm(
                title: S.current.purchase_date,
                value: value,
                border: null,
                onTap:
                    provider.expenseMode ? null : provider.onChangePurchaseDate,
              ),
            ),
            AppSpaces.grayH6,
            listBuilder<String>(
              selector: (_, __) => __.currency?.name,
              builder: (BuildContext context, String value, Widget child) =>
                  ValueSelectForm(
                title: S.current.currency,
                value: value,
                onTap: provider.expenseMode ? null : provider.onChangeCurrency,
              ),
            ),
            Visibility(
              visible: !provider.expenseMode,
              child: FromInputField(
                tip: S.current.cost,
                controller: provider.costController,
                focusNode: provider.costFocusNode,
                keyboardType: TextInputType.numberWithOptions(decimal: true),
                trailing: PressedOpacityButton(
                  onPressed: provider.onShowCostInfo,
                  padding: EdgeInsets.only(right: getDp(10)),
                  child: SvgPicture.asset(
                    A.assetsImagesStyleInformation_1,
                    width: getDp(24),
                    height: getDp(24),
                    fit: BoxFit.contain,
                    color: aceBlueColor,
                  ),
                ),
                inputFormatterList: [
                  doubleInputFormatter,
                ],
              ),
              replacement: ValueSelectForm(
                value: provider.costController.text,
                title: S.current.cost,
                trailing: PressedOpacityButton(
                  onPressed: provider.onShowCostInfo,
                  padding: EdgeInsets.only(right: getDp(10)),
                  child: SvgPicture.asset(
                    A.assetsImagesStyleInformation_1,
                    width: getDp(24),
                    height: getDp(24),
                    fit: BoxFit.contain,
                    color: aceBlueColor,
                  ),
                ),
              ),
            ),
            FromInputField(
              tip: S.current.book_value_after_depreciation_optional,
              helpText: '0%',
              controller: provider.bookValueController,
              focusNode: provider.bookValueFocusNode,
              border: null,
              keyboardType: TextInputType.numberWithOptions(decimal: true),
              inputFormatterList: [
                percentInputFormatter,
              ],
            ),
            AppSpaces.grayH6,
            listBuilder<String>(
              selector: (_, __) => __.depreciationMethod?.name,
              builder: (BuildContext context, String value, Widget child) =>
                  ValueSelectForm(
                title: S.current.depreciation_method,
                value: value,
                onTap: provider.onChangeDepreciationMethod,
              ),
            ),
            FromInputField(
              controller: provider.lifeSpanController,
              focusNode: provider.lifeSpanFocusNode,
              inputFormatterList: [
                intInputFormatter,
              ],
              keyboardType: TextInputType.numberWithOptions(decimal: true),
              tip: S.current.total_useful_life_months,
            ),
            NormalFormWrapper(
              child:
                  listBuilder<Tuple2<List<String>, List<OcrAttachmentEntity>>>(
                selector: (_, __) => Tuple2(
                    List.from(__.files), List.from(__.attachments ?? [])),
                builder: (BuildContext context,
                        Tuple2<List<String>, List<OcrAttachmentEntity>> value,
                        Widget child) =>
                    AttachFileForm(
                  onAdd: provider.onAddAttachment,
                  files: value.item1,
                  onSelectFile: provider.onSelectFile,
                  attachments: value.item2,
                  onSelectAttachment: provider.onSelectAttachment,
                ),
              ),
            ),
            FormStatusWidget(
              disable: Padding(
                padding: EdgeInsets.symmetric(horizontal: getDp(35)),
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        _buildLeftTitle(S.current.cost),
                        listBuilder<String>(
                          selector: (_, __) => __.data?.price,
                          builder: (BuildContext context, String value,
                                  Widget child) =>
                              _buildRightTitle(value),
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        _buildLeftTitle(S.current.accumulated_depreciation),
                        listBuilder<String>(
                            selector: (_, __) => __.data?.depreciationTotal,
                            builder: (BuildContext context, String value,
                                    Widget child) =>
                                _buildRightTitle('($value)',
                                    hasBottomLine: true)),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        _buildLeftTitle(S.current.book_value),
                        listBuilder<String>(
                          selector: (_, __) =>
                              CashUtils.formatCashAmount(__.data?.total),
                          // selector: (_, __) => CashUtils.formatCashAmount(
                          //     __.data == null
                          //         ? null
                          //         : (__.data.bookValueAfter *
                          //         __.data.total /
                          //         100)),
                          builder: (BuildContext context, String value,
                                  Widget child) =>
                              _buildRightTitle(value ?? ''),
                        ),
                      ],
                    ),
                    listBuilder<bool>(
                      selector: (_, __) => __.data?.status == 'sold',
                      builder:
                          (BuildContext context, bool value, Widget child) =>
                              Visibility(
                        child: child,
                        visible: value,
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          _buildLeftTitle(S.current.sales_price),
                          listBuilder<String>(
                            selector: (_, __) => __.data?.sellPrice,
                            builder: (BuildContext context, String value,
                                    Widget child) =>
                                _buildRightTitle(value, hasBottomLine: true),
                          ),
                        ],
                      ),
                    ),
                    listBuilder<bool>(
                        selector: (_, __) =>
                            __.data?.status == 'disposed' ||
                            __.data?.status == 'sold',
                        builder:
                            (BuildContext context, bool value, Widget child) =>
                                Visibility(
                                  child: child,
                                  visible: value,
                                ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            listBuilder<String>(
                              selector: (_, __) => __.data?.status,
                              builder: (BuildContext context, String value,
                                      Widget child) =>
                                  _buildLeftTitle(value == 'sold'
                                      ? S.current.gain_loss_from_sale
                                      : S.current.loss_from_disposal),
                            ),
                            listBuilder<Tuple3<bool, String, String>>(
                              selector: (_, __) => Tuple3(
                                  __.data?.status == 'sold',
                                  CashUtils.formatCashAmount(__.data?.total),
                                  CashUtils.formatCashAmount((__.data?.total ??
                                          0.0) -
                                      num.parse(__.data?.sellPrice ?? '0.0'))),
                              builder: (BuildContext context,
                                      Tuple3<bool, String, String> value,
                                      Widget child) =>
                                  _buildRightTitle(value.item1 == true
                                      ? '(${value.item3})'
                                      : value.item2),
                            ),
                          ],
                        )),
                    AppSpaces.h15,
                  ],
                ),
              ),
              enable: Container(),
            ),
            if (provider.data?.assetDepreciations != null)
              FormStatusWidget(
                disable: Visibility(
                  visible: provider.data.assetDepreciations != null,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      AppSpaces.grayH6,
                      Padding(
                        padding: EdgeInsets.symmetric(
                            horizontal: 35, vertical: 12.0),
                        child: Text("Depreciation History",
                            style: TextStyle(
                              color: aceDarkGrayColor,
                              fontSize: getSp(16),
                              fontWeight: FontWeight.w700,
                              height: 18 / 14,
                            )),
                      ),
                      AppSpaces.grayH05,
                      ListView.separated(
                        shrinkWrap: true,
                        itemCount: provider.data.assetDepreciations.length,
                        itemBuilder: (context, i) {
                          AssetDepreciation assetDepreciation =
                              provider.data.assetDepreciations[i];
                          return Padding(
                            padding: const EdgeInsets.symmetric(
                                horizontal: 35.0, vertical: 12),
                            child: Column(
                              children: [
                                if (i == 0)
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        S.current.date,
                                        style: TextStyle(
                                          color: aceDarkGrayColor,
                                        ),
                                      ),
                                      Text(
                                        S.current.amount,
                                        style: TextStyle(
                                          color: aceDarkGrayColor,
                                        ),
                                      )
                                    ],
                                  ),
                                Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Text(
                                      // i == 0
                                      //     ? DateTimeUtils.formatFixedAssetDate(
                                      //         assetDepreciation.startDate,
                                      //         assetDepreciation.endDate)
                                      //     : DateTimeUtils.formatDateTimeFormat(
                                      //         assetDepreciation.endDate,
                                      //         'd MMM yyyy',
                                      DateTimeUtils.formatDateTimeFormat(
                                          assetDepreciation.issuedAt,
                                          'd MMM yyyy'),
                                      style: TextStyle(
                                        color: aceBlackColor,
                                        fontSize: getSp(18),
                                        fontWeight: FontWeight.w700,
                                      ),
                                    ),
                                    Text(
                                      assetDepreciation.total
                                          .toStringAsFixed(2),
                                      style: TextStyle(
                                        color: aceBlackColor,
                                        fontSize: getSp(18),
                                        fontWeight: FontWeight.w700,
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          );
                        },
                        separatorBuilder: (context, i) => AppSpaces.grayH05,
                      ),
                      AppSpaces.grayH05,
                      AppSpaces.h30,
                    ],
                  ),
                ),
                enable: Container(),
              ),
          ],
        ),
      );

  Widget _buildLeftTitle(String title) => Text(
        title,
        style: TextStyle(
          color: aceDarkGrayColor,
          fontSize: getSp(18),
          fontWeight: FontWeight.w700,
          height: 18 / 14,
        ),
      );

  Widget _buildRightTitle(String title, {bool hasBottomLine}) => Container(
        padding:
            EdgeInsets.only(bottom: hasBottomLine == true ? getDp(8) : 0.0),
        decoration: BoxDecoration(
          border: Border(
              bottom: hasBottomLine == true
                  ? BorderSide(
                      color: aceGrayColor,
                      width: getDp(2),
                    )
                  : BorderSide.none),
        ),
        child: Text(
          title,
          style: TextStyle(
            color: aceDarkGrayColor,
            fontSize: getSp(24),
            fontWeight: FontWeight.w700,
            height: 24 / 14,
          ),
        ),
      );
}
